package com.yjhb.android.sbz.v2.dialog

import android.view.View
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.yjhb.android.sbz.R
import com.yjhb.android.sbz.entity.Task
import com.yjhb.android.sbz.tool.Tool
import com.yjhb.android.sbz.v2.mvp.presenter.NowPresenter
import com.yjhb.android.sbz.v2.mvp.view.NowView
import com.jojo.android.zxlib.base.BaseDialog
import com.jojo.android.zxlib.tool.ZxSpanTool
import kotlinx.android.synthetic.main.diglog_now.*
import java.util.ArrayList


/**
 *  创建者 zx
 *  创建时间 2021/5/18 10:16
 */
class NowDialog(fragment: Fragment) : BaseDialog(fragment), NowView {

    private val presenter = lazy { NowPresenter(this) }
    private var tasks: List<Task>? = null

    //当前任务索引
    private var current = 0

    override fun getLayoutId() = R.layout.diglog_now

    override fun init() {

    }

    init {
        regEvent()
        update()
        presenter.value.getNowTask()
    }


    fun regEvent() {
        close_iv?.setOnClickListener { cancel() }
        change_tv?.setOnClickListener {
            tasks?.let {
                if (current < it.size-1) {
                    current++
                    update()
                } else {
                    tasks = null
                    current = 0
                    presenter.value.getNowTask()
                }
            }
        }
        sign_tv?.setOnClickListener {
            tasks?.let {
                if (current < it.size) {
                    Tool.startEditTaskDetailActivity(activity, it[current].id)
                }
            }
        }
    }

    override fun onStop() {
        tasks = null
        super.onStop()
    }

    private fun update() {

        if (tasks == null || current >= tasks!!.size) {
            loading_view?.visibility = View.VISIBLE
            content_layout?.visibility = View.GONE
        } else {
            refresh(tasks!![current])

            loading_view?.visibility = View.GONE
            content_layout?.visibility = View.VISIBLE
        }
    }

    private fun refresh(task: Task) {
        //任务奖励
        money_tv?.let {
            val charSequence = "￥${task.money}"
            it.text = ZxSpanTool.ZoomSpan(charSequence, 0, 1, 0.5f)
        }
        head_iv?.let {
            Glide.with(activity).load(task.avatar)
                    .error(R.mipmap.test_head)
                    .into(it)
        }
        task_name_tv?.text = task.name

    }

    override fun onLoadSuccess(data: ArrayList<Task>) {
        this.tasks = data
        update()
    }

    override fun onFailure(code: Int, msg: String?) {
        update()
    }

}